package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.common.util.RequestUtils;
import com.mars.common.util.TokenUtils;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.module.admin.entity.*;
import com.mars.module.admin.mapper.*;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysOrderRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysOrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单业务层处理
 *
 * @author mars
 * @date 2024-01-24
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysOrderServiceImpl implements ISysOrderService {

    private final SysOrderMapper baseMapper;
    private final SysProductMapper productMapper;
    private final SysOrderDetailsMapper detailsMapper;
    private final SysUserMapper userMapper;
    private final TokenUtils tokenUtils;
    private final SysDictDataMapper dictDataMapper;
    private final SysShopCarMapper shopCarMapper;

    private final String PREFIX = "ORD";

    private String generateOrderNumber() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return PREFIX + sdf.format(new Date());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysOrder add(SysOrderRequest request) {
        SysOrder entity = SysOrder.builder().build();
        BeanUtils.copyProperties(request, entity);
        entity.setSerialno(generateOrderNumber());
        entity.setStatus("0");
        entity.setCreateTime(LocalDateTime.now());
        entity.setCreateUserId(ContextUserInfoThreadHolder.get().getId());
        baseMapper.insert(entity);
        List<SysProduct> productList = request.getProductList();
        for (SysProduct product : productList) {
            BigDecimal price = productMapper.selectById(product.getId()).getPrice();
            SysOrderDetails details = SysOrderDetails.builder().build();
            details.setOrderId(entity.getId());
            details.setAmount(product.getAmount());
            details.setProductId(product.getId());
            details.setPrice(price.multiply(new BigDecimal(product.getAmount())));
            detailsMapper.insert(details);
            //删除购物车里的记录
            if ("1".equals(request.getIsShopCar())) {
                shopCarMapper.delete(new QueryWrapper<SysShopCar>().eq("user_id", ContextUserInfoThreadHolder.get().getId()).eq("product_id", product.getId()));
            }
        }
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        detailsMapper.delete(new QueryWrapper<SysOrderDetails>().eq("order_id", id));
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysOrderRequest request) {
        SysOrder entity = SysOrder.builder().build();
        BeanUtils.copyProperties(request, entity);
        List<SysProduct> productList = request.getProductList();
        if (productList != null && !productList.isEmpty()) {
            for (SysProduct product : productList) {
                SysOrderDetails details = SysOrderDetails.builder().build();
                details.setOrderId(entity.getId());
                details.setAmount(product.getAmount());
                details.setProductId(product.getId());
                details.setPrice(product.getPrice().multiply(new BigDecimal(product.getAmount())));
                detailsMapper.updateById(details);
            }
        }
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysOrder getById(Long id) {
        List<SysOrderDetails> detailsList = detailsMapper.selectList(new QueryWrapper<SysOrderDetails>().eq("order_id", id));
        SysOrder order = baseMapper.selectById(id);
        if (detailsList != null && !detailsList.isEmpty()) {
            for (SysOrderDetails details : detailsList) {
                SysProduct product = productMapper.selectById(details.getProductId());
                details.setProductName(product.getName());
            }
        }
        order.setProductList(detailsList);
        return order;
    }

    @Override
    public PageInfo<SysOrder> pageList(SysOrderRequest request) {
        HttpServletRequest servletRequest = RequestUtils.getRequest();
        Long userId = tokenUtils.getUserId(servletRequest);
        request.setCreateUserId(userId);
        Page<SysOrder> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysOrder> query = this.buildWrapper(request);
        IPage<SysOrder> pageRecord = baseMapper.selectPage(page, query);
        List<SysOrder> records = pageRecord.getRecords();
        List<SysOrder> recordsNew = new ArrayList<>();
        for (SysOrder order : records) {
            SysUser sysUser = userMapper.selectById(order.getCreateUserId());
            SysUser currentUser = userMapper.selectById(ContextUserInfoThreadHolder.get().getId());
            order.setUserName(sysUser == null ? "" : sysUser.getUserName());
            order.setStatusName(getStatusName(order.getStatus(), "order_status"));
            order.setUserType(currentUser.getType().toString());
            recordsNew.add(order);
        }
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }

    private String getStatusName(String value, String type) {
        List<SysDictData> reviewStatus = dictDataMapper.selectList(Wrappers.lambdaQuery(SysDictData.class).eq(SysDictData::getDictType, type).orderByAsc(SysDictData::getDictSort));
        SysDictData sysDictData = reviewStatus.stream().filter(e -> value.equals(e.getDictValue())).findFirst().orElse(null);
        return sysDictData == null ? "" : sysDictData.getDictLabel();
    }

    @Override
    public List<SysOrder> list(SysOrderRequest request) {
        LambdaQueryWrapper<SysOrder> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    @Override
    public void cancelOrder(Long id) {
        SysOrder sysOrder = baseMapper.selectById(id);
        sysOrder.setStatus("3");//取消订单
        baseMapper.updateById(sysOrder);
    }

    private LambdaQueryWrapper<SysOrder> buildWrapper(SysOrderRequest param) {
        LambdaQueryWrapper<SysOrder> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getSerialno())) {
            query.like(SysOrder::getSerialno, param.getSerialno());
        }
        if (StringUtils.isNotBlank(param.getStatus())) {
            query.eq(SysOrder::getStatus, param.getStatus());
        }
        return query;
    }

}
